<template>
	<DialogBox v-model:visible="drawerVisible" :title="`${drawerProps.title}${$t('user_form.dialog_title.user')}`" width="800px">
		<el-form
			v-if="drawerVisible"
			ref="ruleFormRef"
			label-width="100px"
			label-suffix=" :"
			:rules="rules"
			:disabled="drawerProps.isView ? true : false"
			:model="drawerProps.rowData"
			:hide-required-asterisk="drawerProps.isView ? true : false"
		>
			<div class="flex">
				<div class="flex-1">
					<el-form-item :label="$t('user_form.tablist_label.username')" prop="username">
						<el-input
							v-model="drawerProps.rowData!.username"
							:placeholder="$t('user_form.placeholder.username')"
							:disabled="drawerProps.rowData!.id?true:false"
						/>
					</el-form-item>
					<el-form-item :label="$t('user_form.tablist_label.alias')" prop="alias">
						<el-input v-model="drawerProps.rowData!.alias" :placeholder="$t('user_form.placeholder.alias')" />
					</el-form-item>
					<el-form-item :label="$t('user_form.tablist_label.email')" prop="email">
						<el-input v-model="drawerProps.rowData!.email" :placeholder="$t('user_form.placeholder.email')" />
					</el-form-item>
					<el-form-item :label="$t('user_form.tablist_label.mobile')" prop="mobile">
						<el-input v-model="drawerProps.rowData!.mobile" :placeholder="$t('user_form.placeholder.mobile')" />
					</el-form-item>
					<el-form-item :label="$t('user_form.tablist_label.role_id')" prop="roleId">
						<el-select
							v-model="drawerProps.rowData!.roleId"
							:placeholder="$t('user_form.placeholder.role_id')"
							class="w-full"
							:disabled="isLoginUser"
						>
							<el-option v-for="item in roleList" :key="item.roleId" :label="item.roleName" :value="item.id"></el-option>
						</el-select>
					</el-form-item>
					<el-form-item :label="$t('user_form.tablist_label.company')" prop="company">
						<el-input v-model="drawerProps.rowData!.company" :placeholder="$t('user_form.placeholder.company')" />
					</el-form-item>
					<el-form-item :label="$t('user_form.tablist_label.status')" prop="status">
						<el-switch
							v-model="drawerProps.rowData!.status"
							:active-value="'1'"
							:inactive-value="'0'"
							:disabled="isLoginUser"
						></el-switch>
					</el-form-item>
					<template v-if="publicStore.userInfo.userId == '1'">
						<el-form-item :label="$t('user_form.placeholder.home')" prop="home">
							<el-input v-model="userLogo.home" placeholder="http://ssiot.cc:9000">
								<template #append v-if="userLogo.home">
									<el-link type="primary" @click="gotoPage"> {{ $t("user_form.link.access") }} </el-link>
								</template>
							</el-input>
						</el-form-item>
					</template>
					<el-form-item :label="$t('user_form.tablist_label.description')" prop="description">
						<el-input
							v-model="drawerProps.rowData!.description"
							type="textarea"
							:placeholder="$t('user_form.placeholder.description')"
						/>
					</el-form-item>
				</div>
				<div class="flex-1" v-if="!isLoginUser">
					<!-- <el-form-item label="分组" prop="parentId">
				<el-tree-select v-model="drawerProps.rowData!.parentId" :data="menuId" check-strictly placeholder="选择分组" clearable />
			</el-form-item> -->
					<el-form-item label="" prop="deptIds">
						<TreeFilter
							v-if="drawerVisible"
							class="h-96 w-full border"
							multiple
							:requestApi="getDeptList"
							id="id"
							label="deptName"
							:dataCallback="dataCallback"
							:defaultValue="deptId"
							:isCheckStrictly="isCheckStrictly"
							@change="changeDeptId"
							@tree-ref-mounted="isCheckStrictly = false"
						/>
					</el-form-item>
				</div>
			</div>
		</el-form>
		<template #footer>
			<el-button @click="drawerVisible = false">{{ $t("user_form.btn.cancel") }}</el-button>
			<el-button type="primary" v-show="!drawerProps.isView" @click="handleSubmit">{{ $t("user_form.btn.confirm") }}</el-button>
		</template>
	</DialogBox>
</template>

<script setup lang="ts" name="UserDrawer">
import { getDeptList } from "@/api/modules/dept";
import { getRoleList } from "@/api/modules/role";
import { getLogo, getUser, saveLogo } from "@/api/modules/user";
import DialogBox from "@/components/DialogBox";
import TreeFilter from "@/components/TreeFilter/index.vue";
import { PublicStore } from "@/stores/modules/public";
import { openWin } from "@/utils/routerUtil";
import { showTips } from "@/utils/util";
import { FormInstance } from "element-plus";
import { ComponentInternalInstance, getCurrentInstance, reactive, ref } from "vue";
import { UserModel } from "../interface";
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const publicStore = PublicStore();
const isLoginUser = ref<boolean>(false);
const rules = reactive<any>({});
interface DrawerProps {
	title?: String;
	isView: Boolean;
	rowData?: UserModel;
	api?: (params: any) => Promise<any>;
	getTableList?: () => Promise<any>;
}

// drawer框状态
const drawerVisible = ref(false);
const drawerProps = ref<DrawerProps>({
	isView: false,
	title: ""
});

const userLogo = reactive<any>({
	home: "",
	systemName: "",
	logo: ""
});
const saveHome = async (id: string) => {
	//admin不设置
	if (!id || id == "1") {
		return;
	}
	// if (userLogo.home && !userLogo.home.startsWith("http")) {
	// 	userLogo.home = "http://" + userLogo.home;
	// }
	await saveLogo({
		userId: id,
		systemName: userLogo.systemName,
		logo: userLogo.logo,
		home: userLogo.home
	});
};
const gotoPage = () => {
	let token = "";
	if (RegExp(/\?.+=.*/).test(userLogo.home)) {
		token = `&token=${publicStore.token}`;
	} else {
		token = `/#/?token=${publicStore.token}`;
	}
	openWin(userLogo.home + token);
};
// 接收父组件传过来的参数
const acceptParams = async (params: DrawerProps): Promise<void> => {
	drawerProps.value = params;
	if (params.title == "新增") {
		drawerProps.value.rowData!.status = "1";
	}
	isLoginUser.value = drawerProps.value.rowData?.id == publicStore.userInfo.userId;
	if (!isLoginUser.value) {
		rules.username = [{ required: true, message: proxy?.$t("user_form.rules.username") }];
		rules.roleId = [{ required: true, message: proxy?.$t("user_form.rules.role_id") }];
		rules.deptIds = [{ required: true, message: proxy?.$t("user_form.rules.dept_ids") }];
	} else {
		rules.username = [{ required: true, message: proxy?.$t("user_form.rules.username") }];
	}
	await getDeptId();
	await getRole();
	await getUserLogo();
	drawerVisible.value = true;
};
const getUserLogo = async () => {
	if (drawerProps.value.rowData?.id) {
		let res: any = await getLogo({ userId: drawerProps.value.rowData?.id });
		userLogo.logo = res.result.logo;
		userLogo.home = res.result.home;
		userLogo.systemName = res.result.systemName;
	}
};
// 提交数据（新增/编辑）
const ruleFormRef = ref<FormInstance>();
const handleSubmit = () => {
	ruleFormRef.value!.validate(async valid => {
		if (!valid) return;
		try {
			let { code, message, result } = await drawerProps.value.api!({
				...drawerProps.value.rowData,
				deptIds: deptId.value.toString()
			});
			let ok = showTips(
				code,
				drawerProps.value.rowData?.id ? proxy?.$t("user_form.tips.modify") : proxy?.$t("user_form.tips.add"),
				message
			);
			// ElMessage.success({ message: `${drawerProps.value.title}用户成功！` });
			saveHome(drawerProps.value.rowData?.id || result);
			if (ok) {
				drawerVisible.value = false;
				drawerProps.value.getTableList?.();
			}
		} catch (error) {
			console.log(error);
		}
	});
};

// dataCallback 是对于返回的表格数据做处理，
const dataCallback = (data: any) => {
	return data.records.children;
};
//获取角色分组权限
const deptId = ref<any>([]);
const isCheckStrictly = ref<boolean>();
const getDeptId = async () => {
	if (drawerProps.value.rowData) {
		let { result } = await getUser(drawerProps.value.rowData.username);
		deptId.value = result.deptIds.split(",");
		isCheckStrictly.value = true;
		drawerProps.value.rowData!.deptIds = result.deptIds;
	}
};

//勾选菜单返回数据
const changeDeptId = (data: any) => {
	deptId.value = [...data.checked, ...data.halfChecked].map((item: any) => item.id).filter((item: any) => item != "root");
	drawerProps.value.rowData!.deptIds = deptId.value.toString();
};
//获取角色列表
const roleList = ref<any>();
const getRole = async () => {
	let { result } = await getRoleList({ pageIndex: 1, pageSize: 999 });
	roleList.value = result.records;
};
defineExpose({
	acceptParams
});
</script>
